/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-03-13 10:50:39
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2023-04-12 17:48:18
 */
import { useContext, useEffect, useState } from 'react'
import { StyleSheet, useColorScheme, Alert } from 'react-native'
import { TokenContext } from '../Context'
import appColor from '../../utils/appColor'
import Storage from '../../utils/asyncStorage'
import { Heading, Spinner, Stack, Icon, Input, Button, Pressable } from 'native-base'
import Ionicons from 'react-native-vector-icons/Ionicons'

const Login = ({ navigation }) => {

    const [loginData, setLoginData] = useState({ server: '', username: '', password: '' })
    const [show, setShow] = useState(false)

    const onChangeVal = (prop, val) => {
        setLoginData((v) => {
            const newLoginData = { ...v }
            newLoginData[prop] = val
            return newLoginData
        })
    }

    const { updateToken } = useContext(TokenContext)


    useEffect(() => {
        Storage.getItems(['server', 'username']).then(data => {
            if (!data.length) return
            let server = data[0][1]
            let username = data[1][1]
            const newLoginData = { ...loginData }
            newLoginData.server = server
            newLoginData.username = username
            setLoginData(newLoginData)
        })
    }, [])

    const [loading, setLoading] = useState(false)
    const login = () => {
        const { username, password } = loginData
        if (!(username && password && loginData.server)) return Alert.alert('有未填写项！')
        let baseUrl = 'https://' + loginData.server + '/api'
        setLoading(true)
        fetch(baseUrl + '/login', {
            method: 'POST',
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ username, password })
        }).then((res) => res.json()).then(async rjson => {
            setLoading(false)
            // await Storage.setItem('user', rjson.data)
            // await Storage.setItem('server',  loginData.server)
            // await Storage.setItem('baseUrl', baseUrl)
            await Storage.setItems([['user', rjson.data], ['username', loginData.username], ['server', loginData.server], ['baseUrl', baseUrl]])

            updateToken(rjson.data.token)
            // navigation.navigate('home1')
        }).catch(e => {
            setLoading(false)
            Alert.alert('登录失败！')
        })
    }

    const colorScheme = useColorScheme()


    return (
        <>
            <Stack opacity={loading ? 0.6 : 1} space={5} bgColor={colorScheme === 'dark' ? appColor.darkbg : appColor.lightbg} h='100%' w="100%" alignItems="center" justifyContent="center">
                <Heading size={'md'} color='vigour.700'>PT助手</Heading>
                <Input
                    w={{ base: "75%", md: "25%" }}
                    InputLeftElement={
                        <Icon as={<Ionicons name="server-outline" />} size={5} ml="2" color="muted.400" />
                    }
                    type='text'
                    returnKeyType={'next'}
                    value={loginData.server}
                    onChangeText={(v) => onChangeVal('server', v)}
                    placeholder="服务器" />
                <Input
                    w={{ base: "75%", md: "25%" }}
                    InputLeftElement={
                        <Icon as={<Ionicons name="person-outline" />} size={5} ml="2" color="muted.400" />
                    }
                    type='text'
                    returnKeyType={'next'}
                    value={loginData.username}
                    onChangeText={(v) => onChangeVal('username', v)}
                    placeholder="账号" />
                <Input
                    w={{ base: "75%", md: "25%" }}
                    type={show ? "text" : "password"}
                    InputLeftElement={
                        <Icon as={<Ionicons name='key-outline' />} size={5} ml="2" color="muted.400" />
                    }
                    InputRightElement={
                        <Pressable onPress={() => setShow(!show)}>
                            <Icon as={<Ionicons name={show ? "eye-outline" : "eye-off-outline"} />} size={5} mr="2" color="muted.400" />
                        </Pressable>}
                    returnKeyType={'done'}
                    value={loginData.password}
                    onChangeText={(v) => onChangeVal('password', v)}
                    placeholder="密码" />
                <Button onPress={login}>登 录</Button>
            </Stack>
            {loading ?
                (<Stack space={3} position='absolute' left='1/2' top='1/2' transform={[{ translateX: -20 }]} justifyContent={'center'} alignItems="center">
                    <Spinner size="lg" color={'warning.500'} />
                </Stack>) : null}
        </>
    )
}

const styles = StyleSheet.create({
    page: {
        // height: '100%',
        // display: 'flex',
        // justifyContent: 'center',
        // alignItems: 'center',
    },
    inputItemInput: {
        width: '65%',
        // borderBottomColor: appColor.light3,
        borderBottomWidth: 1,
        marginBottom: 15,
        // backgroundColor: appColor.light2,
        borderRadius: 5,
        paddingHorizontal: 20
    },
    loginBtn: {
        width: '65%'
    }
})

export default Login
